<script setup>
import { ref } from 'vue';
import { useClassIDStore } from '@/stores/classID.js'
const classIDStore = useClassIDStore();
import { conversationService } from '@/api/conversationInfo.js'
import { classInfoService } from '@/api/classInfo.js'
import { allChapterInfoService } from '@/api/allChapterInfo.js'
import { newConversationService } from '@/api/newConversation.js'
import { overConversationService } from '@/api/overConversation.js'
import { allQuestionService } from '@/api/allQuestionInfo.js'
import { askQuestionService } from '@/api/askQuestion.js'
import { questionEvaluateService } from '@/api/questionEvaluate.js'
import { conversationEvaluateService } from '@/api/conversationEvaluate.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { watch } from '@vue/runtime-core'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/lib/common';
const md = new MarkdownIt({
    highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
            try {
                return '<pre><code class="hljs">' +
                    hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                    '</code></pre>';
            } catch (__) { }
        }
        return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
    }
});
const className = ref()
const getClassInfo = async () => {
    let classInfo = await classInfoService(classIDStore.classID);
    className.value = classInfo.data.className
    //console.log(className.value)
}
getClassInfo();
const pageType = ref(0)
const selectData = ref()
const getAllChapterInfo = async () => {
    let chapterResult = await allChapterInfoService(classIDStore.classID);
    selectData.value = chapterResult.data
}
getAllChapterInfo();
const chapterIDvalue = ref('请选择章节')
const showHistory = ref(0)
const historyData = ref()
const textarea = ref('')
const conversationType = ref(0)
let newConversationID
const newConversation = () => {
    if (conversationType.value == 1) {
        ElMessage('请先结束当前对话')
        return
    }
    pageType.value = 2
};
const nowData = ref([])
const sendDisable = ref(false)
let questionContent
let questionID
const newQuestionClick = async () => {
    if (textarea.value == '') {
        ElMessage('请输入内容')
        return
    }
    if (conversationType.value == 0) {
        let tmp = await newConversationService(classIDStore.classID, chapterIDvalue.value);
        console.log(tmp)
        newConversationID = tmp.data.conversationID
        conversationType.value = 1
    }
    sendDisable.value = true
    nowData.value.push({ 'content': textarea.value, 'type': 0 })
    questionContent = textarea.value
    textarea.value = ''
    nowData.value.push({ 'type': 2 })
    let answer = await askQuestionService(newConversationID, questionContent)
    questionID = answer.data.questionID
    questionContent = md.render(answer.data.answerContent)
    //console.log(questionContent)
    if (questionContent == null) {
        questionContent = '服务器繁忙，稍后再试'
    }
    nowData.value[nowData.value.length - 1] = { 'content': questionContent, 'type': 1, 'evaluate': 0 }
    //nowData.value.push({ 'content': questionContent, 'type': 1, 'evaluate': 0 })
    //console.log(nowData[1].value.evaluate)
    sendDisable.value = false
    // setTimeout(() => {

    // }, 2000);//等两秒用于模拟等待回话的时间
};
const newQuestion = async (event) => {
    if (textarea.value == '') {
        ElMessage('请输入内容')
        return
    }
    if (event.shiftKey && event.key === 'Enter') {
        // 处理 shift+enter 的情况，即换行  
        event.preventDefault(); // 防止默认行为（如果有的话）  
        console.log('换行操作');
        return
    }
    if (conversationType.value == 0) {
        let tmp = await newConversationService(classIDStore.classID, chapterIDvalue.value);
        console.log(tmp)
        newConversationID = tmp.data.conversationID
        conversationType.value = 1
    }
    sendDisable.value = true
    nowData.value.push({ 'content': textarea.value, 'type': 0 })
    questionContent = textarea.value
    textarea.value = ''
    nowData.value.push({ 'type': 2 })
    let answer = await askQuestionService(newConversationID, questionContent)
    questionID = answer.data.questionID
    questionContent = md.render(answer.data.answerContent)
    //console.log(questionContent)
    if (questionContent == null) {
        questionContent = '服务器繁忙，稍后再试'
    }
    nowData.value[nowData.value.length - 1] = { 'content': questionContent, 'type': 1, 'evaluate': 0 }
    //console.log(nowData[1].value.evaluate)
    sendDisable.value = false
    // setTimeout(() => {

    // }, 2000);//等两秒用于模拟等待回话的时间
};
const overConversation = () => {
    pageType.value = 0
};
const realOverConversation = () => {
    console.log('已结束')
    overConversationService(newConversationID)
    nowData.value.splice(0)
    conversationType.value = 0
}
const questionEvaluate = (evaContent) => {
    let result = questionEvaluateService(newConversationID, questionID, evaContent);
    console.log(result)
}
const returnHome = () => {
    pageType.value = 3
};
const handleNodeClick = async (data) => {
    //console.log(data)
    if (data.conversationID != null) {
        //console.log(data.conversationID)
        pageType.value = 1
        let tmp = await allQuestionService(data.conversationID);
        console.log(tmp)
        historyData.value = tmp.data.data.map(item => ({
            ...item,
            answerContent: md.render(item.answerContent)
        }));
    }
}
const allData = []
const allConversationData = ref()
const getAllConversationInfo = async () => {
    let chapterResult = await allChapterInfoService(classIDStore.classID);
    selectData.value = chapterResult.data
    for (let i = 0; i < chapterResult.data.length; i++) {
        let conversation = await conversationService(classIDStore.classID, chapterResult.data[i].chapterID);
        let chapterData = {
            label: '',
            children: [
            ]
        };
        chapterData.label = chapterResult.data[i].chapterName;
        for (let j = 0; j < conversation.data.length; j++) {
            chapterData.children.push({ label: conversation.data[j].title, conversationID: conversation.data[j].conversationID })
        }
        console.log(chapterData)
        allData.push(chapterData)
    }
    console.log(allData)
    allConversationData.value = allData
}
getAllConversationInfo()
import { useRouter } from 'vue-router';
const router = useRouter()
watch(pageType, (newValue, oldValue) => {
    console.log('修改了pageType', newValue, oldValue)
    if (oldValue == 2 && conversationType.value == 1) {
        ElMessageBox.confirm(
            '是否离开当前对话，将会结束对话',
            'Warning',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                realOverConversation()
                ElMessageBox.confirm(
                    '请评价对话',
                    {
                        confirmButtonText: '好',
                        cancelButtonText: '坏',
                    }
                )
                    .then(() => {
                        conversationEvaluateService(classIDStore.classID, newConversationID, '1')
                        ElMessage({
                            type: 'success',
                            message: '好评',
                        })
                    })
                    .catch(() => {
                        conversationEvaluateService(classIDStore.classID, newConversationID, '0')
                        ElMessage({
                            type: 'success',
                            message: '差评',
                        })
                    })
                showHistory.value = newValue
                if (newValue == 3) {
                    router.push('/studentHome');
                }
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消结束',
                })
                pageType.value = oldValue
            })
    }
    else {
        showHistory.value = newValue
        console.log(showHistory.value)
        if (newValue == 3) {
            router.push('/studentHome');
        }
    }
})
</script>
<template>
    <!-- 整个聊天面板 -->
    <el-container class="chat-panel" style="background-color: #f5f5dc;">
        <!-- 左侧的会话列表 -->

        <el-aside class="session-panel">
            <div :style="{ height: '100%' }">
                <div :style="{ height: '20%' }">

                    <div class="container">
                        <div class="top-section">
                            <div style="flex-grow: 1; font-size: 20px;">{{ className }}</div>
                            <el-button class="returnButton" @click="returnHome()">返回</el-button>
                        </div>
                        <div class="bottom-section">
                            <el-select v-model="chapterIDvalue" placeholder="请选择章节">
                                <el-option v-for="item in selectData" :key="item.value" :label="item.chapterName"
                                    :value="item.chapterID" />
                            </el-select>
                            <el-button @click="newConversation()"
                                :disabled="chapterIDvalue === '请选择章节' || sendDisable">新建对话</el-button>
                        </div>
                    </div>


                </div>
                <div :style="{ height: '80%' }">
                    <el-scrollbar>
                        <el-tree style="max-width: 600px" :data="allConversationData" @node-click="handleNodeClick" />
                    </el-scrollbar>
                </div>
            </div>

        </el-aside>
        <el-container :style="{ width: '80%' }">
            <el-main :style="{ height: '100vh', width: '100%', border: '2px solid #ccc' }" v v-if="showHistory == 1">
                <el-scrollbar>
                    <div v-for="(item, index) in historyData" :key="index">
                        <el-card shadow="always" style="max-width: 70%;margin: 0 auto;margin-bottom: 15px;">
                            <p class="question">
                            <div v-html="item.questionContent"></div>
                            </p>
                        </el-card>
                        <el-card shadow="always"
                            style=" background-color: #82c1ff;max-width: 70%;margin: 0 auto;margin-bottom: 15px;">
                            <p class="answer">
                            <div v-html="item.answerContent"></div>
                            </p>
                        </el-card>
                    </div>
                </el-scrollbar>

            </el-main>
            <!-- 右侧的消息记录 -->

            <el-main class="message-panel" v-else-if="showHistory == 2">
                <div class="dialog-container">
                    <div class="dialog-content">
                        <el-card v-for="(item, index) in nowData" :key="index"
                            style="max-width: 70%;margin: 0 auto;margin-bottom: 15px;"
                            :class="{ 'user-question': item.type === 0, 'bot-answer': item.type === 1, 'wait': item.type === 2 }">
                            <div v-html="item.content"></div>
                            <div v-if="item.type == 1">
                                <hr />
                                <div>
                                    <el-radio-group v-model="item.evaluate" class="ml-4" :disabled="item.evaluate != 0">
                                        <el-radio label="1" size="small" @click="questionEvaluate(1)">好</el-radio>
                                        <el-radio label="2" size="small" @click="questionEvaluate(2)">差</el-radio>
                                    </el-radio-group>
                                </div>
                            </div>
                            <div v-if="item.type == 2">
                                <img src="./wait.gif" class="small-gif" />
                            </div>
                        </el-card>
                    </div>
                    <div class="user-input">
                        <el-input v-model="textarea" show-word-limit :autosize="{ minRows: 4, maxRows: 6 }"
                            type="textarea" placeholder="请输入问题" @keyup.enter="newQuestion" :disabled="sendDisable" />
                        <div class="vertical-buttons">
                            <el-button class="sendButton" @click="newQuestionClick()"
                                :disabled="sendDisable">发送</el-button>
                            <el-button class="overButton" @click="overConversation()"
                                :disabled="sendDisable || nowData.length == 0">结束对话</el-button>
                            <div class="tag">
                                <el-tag type="primary" v-if="sendDisable == false">请输入问题</el-tag>
                                <el-tag type="warning" v-else-if="sendDisable == true">请等待</el-tag>
                            </div>
                        </div>

                        <!-- <el-button @click="newQuestion()" :disabled="sendDisable">发送</el-button>
                        <el-button @click="overConversation()"
                            :disabled="sendDisable || nowData.length == 0">结束对话</el-button> -->
                        <!-- <div>
                            <el-tag type="primary">Tag 1</el-tag>
                            <el-tag type="success">Tag 2</el-tag>
                            <el-tag type="info">Tag 3</el-tag>
                            <el-tag type="warning">Tag 4</el-tag>
                            <el-tag type="danger">Tag 5</el-tag>
                        </div> -->
                    </div>
                </div>
            </el-main>
        </el-container>
    </el-container>
</template>
<style lang="scss" scoped>
.chat-panel {
    /* 聊天面板flex布局，让会话列表和聊天记录左右展示 */
    display: flex;

    .session-panel {
        background-color: #0997F7;
        width: 20%;
        height: 100vh;
        padding: 20px;

        //border-right: 1px solid rgba(black, 0.07);
        .container {
            display: flex;
            flex-direction: column;
        }

        .top-section {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .bottom-section {
            display: flex;
            align-items: center;
        }

        .el-select {
            margin-right: 50px;
            margin-top: 20px;
            /* Adjust as needed */
        }

    }

    .question {
        text-align: right;
    }

    .answer {
        text-align: left;
    }

    .el-card {
        border-radius: 20px;
    }

    .message-panel {
        display: flex;
        width: 80%;
        height: 100vh;

        .dialog-container {
            width: 100%;
            display: flex;
            flex-direction: column;
        }

        .dialog-content {
            width: 100%;
            height: 85%;
            //flex: 1;
            overflow-y: auto;
            /* 当内容超出高度时显示滚动条 */
        }

        .user-input {
            display: flex;
            margin: 0 auto;
            width: 70%;
            height: 15%;

            .vertical-buttons {
                //display: flex;
                flex-direction: column;
            }

            .sendButton {
                margin-top: -1px;
                /* 可根据需要调整按钮之间的间距 */
            }

            .overButton {
                margin-top: 7px;
                /* 负边距向上移动按钮 */
                margin-left: -1px;
                /* 负边距向左移动按钮 */
                /* 可根据需要调整按钮之间的间距 */
            }

            .tag {
                margin-top: 3px;
            }

        }

        .user-question {
            text-align: right;
        }

        .bot-answer {
            background-color: #82c1ff;
            text-align: left;
        }

        .wait {
            background-color: #82c1ff;
            display: flex;
            justify-content: center;
            align-items: center;

            .small-gif {
                width: 30px;
                /* 调整为期望的宽度 */
                height: 30px;
                /* 调整为期望的高度 */
            }

        }
    }
}
</style>